package com.xky.ui.module.salesManagement.update;

import com.xky.pojo.SalesShipments;
import com.xky.pojo.SalesOrders;
import com.xky.utils.DBUtils;
import com.xky.ui.module.salesManagement.select.SelectSalesShipment;
import com.xky.ui.module.salesManagement.select.SelectSalesOrder;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 * 修改销售发货单信息的窗口类
 * 提供以下功能：
 * 1. 通过发货单号查询发货单信息
 * 2. 修改发货单的基本信息
 * 3. 支持查看模式（只读）
 * 4. 实时验证输入数据
 * 5. 异步处理数据库操作
 */
public class UpdateSalesShipment extends JFrame {
    // 界面常量
    private static final int WINDOW_WIDTH = 480;
    private static final int WINDOW_HEIGHT = 680;
    private static final int FIELD_HEIGHT = 35;
    private static final int BUTTON_WIDTH = 120;
    private static final int BUTTON_HEIGHT = 40;
    
    // 字体常量
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 28);
    private static final Font LABEL_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font FIELD_FONT = new Font("微软雅黑", Font.PLAIN, 14);
    private static final Font HINT_FONT = new Font("微软雅黑", Font.ITALIC, 14);
    private static final Font NOTE_FONT = new Font("微软雅黑", Font.ITALIC, 12);
    
    // 颜色常量
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);
    private static final Color SECONDARY_COLOR = new Color(240, 248, 255);
    private static final Color BUTTON_COLOR = new Color(100, 149, 237);
    private static final Color QUERY_BUTTON_COLOR = new Color(46, 204, 113);
    private static final Color CANCEL_BUTTON_COLOR = new Color(231, 76, 60);
    private static final Color HINT_COLOR = Color.GRAY;
    private static final Color NOTE_COLOR = new Color(102, 102, 102);

    // 日期格式化
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    // 运输方式选项
    private static final String[] SHIPPING_METHODS = {"空运", "陆运", "海运", "快递"};
    
    // 状态选项
    private static final String[] STATUS_OPTIONS = {"待发货", "已发货", "运输中", "已送达", "已签收"};
    
    // 界面组件
    private JPanel mainPanel, formPanel, buttonPanel;
    private JTextField shipmentNumberField, orderIdField, warehouseIdField,
            shipDateField, carrierField, trackingNumberField, totalAmountField, taxAmountField;
    private JComboBox<String> shippingMethodCombo, statusCombo;
    private JTextArea notesArea;
    private JButton searchButton, updateButton, cancelButton;
    
    // 当前编辑的发货单
    private SalesShipments currentShipment;
    
    public UpdateSalesShipment() {
        this(-1);
    }
    
    public UpdateSalesShipment(int shipmentId) {
        this(shipmentId, false);
    }
    
    public UpdateSalesShipment(int shipmentId, boolean readOnly) {
        setTitle(readOnly ? "查看销售发货单信息" : "修改销售发货单信息");
        setSize(450, 600); // 调整窗口大小
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        init();

        if (shipmentId > 0) {
            // 隐藏搜索面板
            shipmentNumberField.setEnabled(false);
            searchButton.setEnabled(false);
            Component[] components = mainPanel.getComponents();
            for (Component component : components) {
                if (component instanceof JPanel) {
                    JPanel panel = (JPanel) component;
                    if (panel.getLayout() instanceof BorderLayout) {
                        Component centerComponent = ((BorderLayout) panel.getLayout()).getLayoutComponent(BorderLayout.CENTER);
                        if (centerComponent instanceof JPanel) {
                            Component searchCard = ((JPanel) centerComponent).getComponent(0);
                            if (searchCard instanceof JPanel) {
                                searchCard.setVisible(false);
                            }
                        }
                    }
                }
            }


            // 在后台线程中执行查询
            SwingWorker<SalesShipments, Void> worker = new SwingWorker<>() {
                @Override
                protected SalesShipments doInBackground() {
                    try {
                        Thread.sleep(500);
                        List<SalesShipments> shipments = SelectSalesShipment.selectById(shipmentId);
                        return shipments != null && !shipments.isEmpty() ? shipments.get(0) : null;
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        return null;
                    }
                }

                @Override
                protected void done() {
                    try {
                        currentShipment = get();
                        if (currentShipment != null) {
                            populateForm(currentShipment);
                            setFormFieldsEnabled(!readOnly);
                        } else {
                            showWarning("未找到ID为 " + shipmentId + " 的发货单记录");
                            clearForm();
                            setFormFieldsEnabled(false);
                        }
                    } catch (Exception ex) {
                        showError("加载发货单时发生错误: " + ex.getMessage());
                        ex.printStackTrace();
                    }
                }
            };
            worker.execute();
        }

        setVisible(true);
    }

    private void init() {
        // 创建主面板，使用浅蓝色背景
        mainPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                Color color1 = new Color(236, 245, 255);
                Color color2 = new Color(245, 250, 255);
                GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2);
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        mainPanel.setLayout(new BorderLayout(10, 10));
        mainPanel.setBorder(new EmptyBorder(15, 20, 15, 20));

        // 顶部标题面板
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);

        // 简化标题
        JLabel titleLabel = new JLabel("修改销售发货单信息", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 22));
        titleLabel.setForeground(new Color(70, 130, 180));
        
        // 添加副标题
        JLabel subtitleLabel = new JLabel("请输入发货单号查询后再修改", JLabel.CENTER);
        subtitleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        subtitleLabel.setForeground(new Color(120, 120, 120));
        
        JPanel titlePanel = new JPanel(new BorderLayout(0, 5));
        titlePanel.setOpaque(false);
        titlePanel.add(titleLabel, BorderLayout.NORTH);
        titlePanel.add(subtitleLabel, BorderLayout.CENTER);
        
        // 添加分隔线
        JSeparator separator = new JSeparator();
        separator.setForeground(new Color(200, 215, 230));
        
        headerPanel.add(titlePanel, BorderLayout.NORTH);
        headerPanel.add(separator, BorderLayout.SOUTH);
        headerPanel.setBorder(new EmptyBorder(0, 0, 15, 0));

        mainPanel.add(headerPanel, BorderLayout.NORTH);

        // 中部搜索和表单面板
        JPanel centerPanel = new JPanel(new BorderLayout(0, 15));
        centerPanel.setOpaque(false);

        // 搜索面板 - 简化设计
        JPanel searchCard = new JPanel();
        searchCard.setLayout(new BoxLayout(searchCard, BoxLayout.X_AXIS));
        searchCard.setOpaque(false);
        searchCard.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 215, 230), 1, true),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        
        JLabel searchLabel = new JLabel("发货单号");
        searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        searchLabel.setForeground(new Color(70, 130, 180));
        
        shipmentNumberField = new JTextField(15);
        shipmentNumberField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        shipmentNumberField.setPreferredSize(new Dimension(180, 30));
        
        searchButton = new JButton("查询");
        searchButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        searchButton.setBackground(new Color(46, 204, 113));
        searchButton.setForeground(Color.WHITE);
        searchButton.setBorderPainted(false);
        searchButton.setFocusPainted(false);
        searchButton.setPreferredSize(new Dimension(80, 30));
        searchButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

        searchCard.add(searchLabel);
        searchCard.add(Box.createHorizontalStrut(10));
        searchCard.add(shipmentNumberField);
        searchCard.add(Box.createHorizontalStrut(10));
        searchCard.add(searchButton);

        centerPanel.add(searchCard, BorderLayout.NORTH);

        // 表单面板 - 简化设计
        JPanel formCard = new JPanel();
        formCard.setLayout(new BorderLayout());
        formCard.setOpaque(false);
        formCard.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 215, 230), 1, true),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));

        formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);

        // 创建表单字段
        createFormFields();

        formCard.add(formPanel, BorderLayout.CENTER);

        centerPanel.add(formCard, BorderLayout.CENTER);
        mainPanel.add(centerPanel, BorderLayout.CENTER);

        // 底部按钮面板 - 简化设计
        buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
        buttonPanel.setOpaque(false);
        
        updateButton = new JButton("更新");
        updateButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        updateButton.setPreferredSize(new Dimension(100, 35));
        updateButton.setBackground(new Color(70, 130, 180));
        updateButton.setForeground(Color.WHITE);
        updateButton.setBorderPainted(false);
        updateButton.setFocusPainted(false);
        updateButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

        cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        cancelButton.setPreferredSize(new Dimension(100, 35));
        cancelButton.setBackground(new Color(231, 76, 60));
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setBorderPainted(false);
        cancelButton.setFocusPainted(false);
        cancelButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        buttonPanel.add(updateButton);
        buttonPanel.add(cancelButton);
        
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);
                    
        // 禁用表单字段，直到用户搜索到发货单
        setFormFieldsEnabled(false);

        // 添加事件监听器
        addEventListeners();
    }

    /**
     * 创建表单字段
     */
    private void createFormFields() {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(8, 8, 8, 8);

        Font labelFont = new Font("微软雅黑", Font.BOLD, 14);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 14);

        // 创建并添加字段
        orderIdField = createStyledTextField(fieldFont);
        warehouseIdField = createStyledTextField(fieldFont);
        shipDateField = createStyledTextField(fieldFont);
        carrierField = createStyledTextField(fieldFont);
        trackingNumberField = createStyledTextField(fieldFont);
        
        // 财务信息字段
        totalAmountField = createStyledTextField(fieldFont);
        totalAmountField.setEditable(false);
        totalAmountField.setBackground(new Color(245, 250, 255));
        
        taxAmountField = createStyledTextField(fieldFont);
        taxAmountField.setEditable(false);
        taxAmountField.setBackground(new Color(245, 250, 255));

        // 创建下拉框
        String[] shippingMethods = {"空运", "陆运", "海运", "快递"};
        shippingMethodCombo = new JComboBox<>(shippingMethods);
        styleComboBox(shippingMethodCombo, fieldFont);

        String[] statuses = {"待发货", "已发货", "运输中", "已送达", "已签收"};
        statusCombo = new JComboBox<>(statuses);
        styleComboBox(statusCombo, fieldFont);

        // 创建备注文本区域
        notesArea = new JTextArea(3, 20);
        notesArea.setFont(fieldFont);
        notesArea.setLineWrap(true);
        notesArea.setWrapStyleWord(true);
        JScrollPane notesScrollPane = new JScrollPane(notesArea);
        notesScrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 215, 230)));

        // 添加字段到面板
        int row = 0;
        addFormFieldWithAsterisk(row++, "发货仓库ID", warehouseIdField, labelFont, true);
        addFormFieldWithAsterisk(row++, "发货日期", shipDateField, labelFont, true);
        addFormFieldWithAsterisk(row++, "承运商", carrierField, labelFont, true);
        addFormFieldWithAsterisk(row++, "物流单号", trackingNumberField, labelFont, true);
        addFormFieldWithAsterisk(row++, "运输方式", shippingMethodCombo, labelFont, true);
        addFormFieldWithAsterisk(row++, "状态", statusCombo, labelFont, true);
        addFormField(row++, "商品总额", totalAmountField, labelFont);
        addFormField(row++, "税额", taxAmountField, labelFont);
        addFormField(row++, "备注", notesScrollPane, labelFont);

        // 添加实时验证
        addFieldValidation(orderIdField, "订单ID", true);
        addFieldValidation(warehouseIdField, "仓库ID", true);
        addFieldValidation(shipDateField, "发货日期", true);
        addFieldValidation(carrierField, "承运商", true);
        addFieldValidation(trackingNumberField, "物流单号", true);
        
        // 为日期字段添加特殊验证
        shipDateField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                validateDateField();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                validateDateField();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                validateDateField();
        }
        });
    }

    private JTextField createStyledTextField(Font font) {
        JTextField field = new JTextField();
        field.setFont(font);
        field.setPreferredSize(new Dimension(250, 30));
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 215, 230)),
                BorderFactory.createEmptyBorder(3, 5, 3, 5)
        ));
        return field;
    }

    private void styleComboBox(JComboBox<String> comboBox, Font font) {
        comboBox.setFont(font);
        comboBox.setPreferredSize(new Dimension(250, 30));
        comboBox.setBackground(Color.WHITE);
        comboBox.setBorder(BorderFactory.createLineBorder(new Color(200, 215, 230)));
    }

    private void addFormField(int row, String labelText, JComponent field, Font labelFont) {
        addFormFieldWithAsterisk(row, labelText, field, labelFont, false);
    }

    private void addFormFieldWithAsterisk(int row, String labelText, JComponent field, Font labelFont, boolean required) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.weightx = 0.3;
        gbc.anchor = GridBagConstraints.WEST;

        JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 0));
        labelPanel.setOpaque(false);
        
        JLabel label = new JLabel(labelText);
        label.setFont(labelFont);
        label.setForeground(new Color(70, 130, 180));
        labelPanel.add(label);
        
        if (required) {
            JLabel asterisk = new JLabel(" *");
            asterisk.setFont(labelFont);
            asterisk.setForeground(Color.RED);
            labelPanel.add(asterisk);
        }
        
        formPanel.add(labelPanel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.7;
        formPanel.add(field, gbc);
    }

    /**
     * 启用或禁用表单字段
     */
    private void setFormFieldsEnabled(boolean enabled) {
        orderIdField.setEnabled(enabled);
        warehouseIdField.setEnabled(enabled);
        shipDateField.setEnabled(enabled);
        carrierField.setEnabled(enabled);
        trackingNumberField.setEnabled(enabled);
        shippingMethodCombo.setEnabled(enabled);
        statusCombo.setEnabled(enabled);
        notesArea.setEnabled(enabled);
        updateButton.setEnabled(enabled);
        
        // 财务字段始终保持不可编辑状态
        totalAmountField.setEnabled(false);
        taxAmountField.setEnabled(false);
    }

    /**
     * 添加事件监听器
     */
    private void addEventListeners() {
        // 查询按钮事件
        searchButton.addActionListener(e -> {
            String shipmentNumber = shipmentNumberField.getText().trim();
            if (shipmentNumber.isEmpty()) {
                showWarning("请输入发货单号");
                shipmentNumberField.requestFocus();
                return;
            }

            // 在后台线程中执行查询
            SwingWorker<List<SalesShipments>, Void> worker = new SwingWorker<>() {
                @Override
                protected List<SalesShipments> doInBackground() {
                    try {
                        return SelectSalesShipment.selectByShipmentNumber(shipmentNumber);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        return null;
                    }
                }

                @Override
                protected void done() {
                    try {
                        List<SalesShipments> shipments = get();
                        if (shipments != null && !shipments.isEmpty()) {
                            if (shipments.size() > 1) {
                                // 如果找到多个匹配项，显示选择对话框
                                SalesShipments selected = showSelectionDialog(shipments);
                                if (selected != null) {
                                    currentShipment = selected;
                                    populateForm(currentShipment);
                                    setFormFieldsEnabled(true);
                                }
                            } else {
                                // 只找到一个匹配项
                                currentShipment = shipments.get(0);
                                populateForm(currentShipment);
                                setFormFieldsEnabled(true);
                            }
                        } else {
                            showWarning("未找到发货单号包含 " + shipmentNumber + " 的记录");
                            clearForm();
                            setFormFieldsEnabled(false);
                        }
                    } catch (Exception ex) {
                        showError("查询发货单时发生错误: " + ex.getMessage());
                        ex.printStackTrace();
                    }
                }
            };
            worker.execute();
        });

        // 更新按钮事件
        updateButton.addActionListener(e -> {
            if (!validateForm()) {
                return;
            }

            int option = JOptionPane.showConfirmDialog(this,
                    "确定要更新此发货单信息吗？", "确认更新",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (option != JOptionPane.YES_OPTION) {
                return;
            }

            // 显示等待对话框
            JDialog waitDialog = showWaitingDialog("正在更新发货单信息...");

            // 在后台线程中执行更新
            SwingWorker<Boolean, Void> worker = new SwingWorker<>() {
                @Override
                protected Boolean doInBackground() {
                    try {
                        // 更新当前发货单对象
                        updateShipmentFromForm();
                        return true;
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        return false;
                    }
                }

                @Override
                protected void done() {
                    waitDialog.dispose();
                    try {
                        boolean success = get();
                        if (success) {
                            showInfo("发货单信息更新成功！");
                            dispose();
                        } else {
                            showError("发货单信息更新失败，请重试");
                        }
                    } catch (Exception ex) {
                        showError("更新发货单时发生错误: " + ex.getMessage());
                        ex.printStackTrace();
                }
            }
            };
            worker.execute();
        });

        // 取消按钮事件
        cancelButton.addActionListener(e -> dispose());

        // 为发货单号文本框添加回车键事件
        shipmentNumberField.addActionListener(e -> searchButton.doClick());
    }

    /**
     * 显示等待对话框
     */
    private JDialog showWaitingDialog(String message) {
        JDialog dialog = new JDialog(this, "请稍候", true);
        dialog.setLayout(new BorderLayout());
        dialog.setSize(300, 100);
        dialog.setLocationRelativeTo(this);
        dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        dialog.setUndecorated(true); // 无边框

        // 创建半透明的圆角面板
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(new Color(255, 255, 255, 220));
                g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);
                g2.dispose();
            }
        };
        panel.setLayout(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(15, 25, 15, 25));

        // 消息标签
        JLabel messageLabel = new JLabel(message, JLabel.CENTER);
        messageLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        panel.add(messageLabel, BorderLayout.NORTH);

        // 进度条
        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);
        progressBar.setPreferredSize(new Dimension(200, 5));
        panel.add(progressBar, BorderLayout.CENTER);

        dialog.add(panel);

        // 在新线程中显示对话框
        new Thread(() -> dialog.setVisible(true)).start();

        return dialog;
    }

    /**
     * 填充表单数据
     */
    private void populateForm(SalesShipments shipment) {
        System.out.println("开始填充表单数据...");
        orderIdField.setText(String.valueOf(shipment.getOrderId()));
        warehouseIdField.setText(String.valueOf(shipment.getWarehouseId()));
        shipDateField.setText(shipment.getShipmentDate() != null ? shipment.getShipmentDate().format(DATE_FORMATTER) : "");
        carrierField.setText(shipment.getCarrier());
        trackingNumberField.setText(shipment.getTrackingNumber());
        shippingMethodCombo.setSelectedItem(shipment.getShippingMethod());
        statusCombo.setSelectedItem(shipment.getStatus());
        notesArea.setText(shipment.getNotes());
        
        // 获取并显示订单的财务信息
        if (shipment.getOrderId() != null) {
            System.out.println("发现有效的订单ID: " + shipment.getOrderId());
            getOrderInfoAndUpdateFields(shipment.getOrderId());
        } else {
            System.out.println("警告: 发货单没有关联订单ID");
            totalAmountField.setText("");
            taxAmountField.setText("");
        }
    }

    /**
     * 从表单更新发货单对象
     */
    private void updateShipmentFromForm() {
        if (currentShipment == null) {
            currentShipment = new SalesShipments();
        }

        currentShipment.setOrderId(Integer.parseInt(orderIdField.getText().trim()));
        currentShipment.setWarehouseId(Integer.parseInt(warehouseIdField.getText().trim()));
        currentShipment.setShipmentDate(LocalDate.parse(shipDateField.getText().trim(), DATE_FORMATTER));
        currentShipment.setCarrier(carrierField.getText().trim());
        currentShipment.setTrackingNumber(trackingNumberField.getText().trim());
        currentShipment.setShippingMethod((String) shippingMethodCombo.getSelectedItem());
        currentShipment.setStatus((String) statusCombo.getSelectedItem());
        currentShipment.setNotes(notesArea.getText().trim());
        
        // 更新数据库
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtils.getConnection();
            String sql = "UPDATE sales_shipments SET order_id=?, warehouse_id=?, shipment_date=?, " +
                        "carrier=?, tracking_number=?, shipping_method=?, status=?, notes=?, " +
                        "updated_time=? WHERE shipment_id=?";
            
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, currentShipment.getOrderId());
            pstmt.setInt(2, currentShipment.getWarehouseId());
            pstmt.setDate(3, java.sql.Date.valueOf(currentShipment.getShipmentDate()));
            pstmt.setString(4, currentShipment.getCarrier());
            pstmt.setString(5, currentShipment.getTrackingNumber());
            pstmt.setString(6, currentShipment.getShippingMethod());
            pstmt.setString(7, currentShipment.getStatus());
            pstmt.setString(8, currentShipment.getNotes());
            pstmt.setTimestamp(9, Timestamp.valueOf(LocalDateTime.now()));
            pstmt.setInt(10, currentShipment.getShipmentId());
            
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected == 0) {
                throw new SQLException("更新发货单失败，未找到记录。");
            }
        } catch (SQLException e) {
            throw new RuntimeException("更新发货单时发生错误: " + e.getMessage(), e);
        } finally {
            DBUtils.closeAll(conn, pstmt, null);
        }
    }

    /**
     * 验证表单数据
     */
    private boolean validateForm() {
        boolean isValid = true;
        
        // 验证订单ID
        if (!validateNumericField(orderIdField, "订单ID")) {
            isValid = false;
        }

        // 验证仓库ID
        if (!validateNumericField(warehouseIdField, "仓库ID")) {
            isValid = false;
        }

        // 验证发货日期
        String shipDate = shipDateField.getText().trim();
        if (shipDate.isEmpty()) {
            showWarning("发货日期不能为空");
            shipDateField.requestFocus();
            isValid = false;
        } else {
            try {
                LocalDate.parse(shipDate, DATE_FORMATTER);
            } catch (DateTimeParseException e) {
                showWarning("发货日期格式不正确，请使用yyyy-MM-dd格式");
                shipDateField.requestFocus();
                isValid = false;
            }
        }

        // 验证承运商
        if (carrierField.getText().trim().isEmpty()) {
            showWarning("承运商不能为空");
            carrierField.requestFocus();
            isValid = false;
        }

        // 验证物流单号
        if (trackingNumberField.getText().trim().isEmpty()) {
            showWarning("物流单号不能为空");
            trackingNumberField.requestFocus();
            isValid = false;
        }

        return isValid;
    }

    private boolean validateNumericField(JTextField field, String fieldName) {
        String value = field.getText().trim();
        if (value.isEmpty()) {
            showWarning(fieldName + "不能为空");
            field.requestFocus();
            return false;
        }
        try {
            Integer.parseInt(value);
        } catch (NumberFormatException e) {
            showWarning(fieldName + "必须是数字");
            field.requestFocus();
            return false;
        }
        return true;
    }

    /**
     * 清空表单
     */
    private void clearForm() {
        orderIdField.setText("");
        warehouseIdField.setText("");
        shipDateField.setText("");
        carrierField.setText("");
        trackingNumberField.setText("");
        shippingMethodCombo.setSelectedIndex(0);
        statusCombo.setSelectedIndex(0);
        totalAmountField.setText("");
        taxAmountField.setText("");
        notesArea.setText("");
    }
    
    /**
     * 检查订单数据是否有效
     * @param order 订单对象
     * @return 是否有效
     */
    private boolean isValidOrderData(SalesOrders order) {
        if (order == null) {
            System.out.println("订单对象为空");
            return false;
        }
        
        System.out.println("订单ID: " + order.getOrderId());
        System.out.println("订单编号: " + order.getOrderNumber());
        
        // 检查商品总额
        if (order.getSubtotal() == null) {
            System.out.println("商品总额为空");
            return false;
        }
        System.out.println("商品总额: " + order.getSubtotal());
        
        // 检查税额
        if (order.getTaxAmount() == null) {
            System.out.println("税额为空");
            return false;
        }
        System.out.println("税额: " + order.getTaxAmount());
        
        return true;
    }
    
    /**
     * 获取订单信息并更新财务字段
     * @param orderId 订单ID
     */
    private void getOrderInfoAndUpdateFields(int orderId) {
        try {
            System.out.println("正在获取订单ID为 " + orderId + " 的订单信息...");
            List<SalesOrders> orders = SelectSalesOrder.selectById(orderId);
            if (orders != null && !orders.isEmpty()) {
                SalesOrders order = orders.get(0);
                System.out.println("找到订单: " + order.getOrderNumber());
                
                if (isValidOrderData(order)) {
                    // 设置商品总额和税额
                    totalAmountField.setText(order.getSubtotal().toString());
                    taxAmountField.setText(order.getTaxAmount().toString());
                    System.out.println("已成功设置商品总额: " + order.getSubtotal() + " 和税额: " + order.getTaxAmount());
                } else {
                    // 订单数据无效，尝试直接查询数据库
                    System.out.println("订单数据无效，尝试直接查询数据库...");
                    Connection conn = null;
                    PreparedStatement pstmt = null;
                    ResultSet rs = null;
                    
                    try {
                        conn = DBUtils.getConnection();
                        String sql = "SELECT subtotal, tax_amount FROM sales_orders WHERE order_id = ?";
                        pstmt = conn.prepareStatement(sql);
                        pstmt.setInt(1, orderId);
                        rs = pstmt.executeQuery();
                        
                        if (rs.next()) {
                            // 获取数据
                            java.math.BigDecimal subtotal = rs.getBigDecimal("subtotal");
                            java.math.BigDecimal taxAmount = rs.getBigDecimal("tax_amount");
                            
                            // 设置字段
                            if (subtotal != null) {
                                totalAmountField.setText(subtotal.toString());
                                System.out.println("直接查询设置商品总额: " + subtotal);
                            } else {
                                totalAmountField.setText("");
                                System.out.println("直接查询的商品总额为空");
                            }
                            
                            if (taxAmount != null) {
                                taxAmountField.setText(taxAmount.toString());
                                System.out.println("直接查询设置税额: " + taxAmount);
                            } else {
                                taxAmountField.setText("");
                                System.out.println("直接查询的税额为空");
                            }
                        } else {
                            System.out.println("未找到订单记录");
                            totalAmountField.setText("");
                            taxAmountField.setText("");
                        }
                    } catch (SQLException e) {
                        System.out.println("直接查询数据库失败: " + e.getMessage());
                        e.printStackTrace();
                    } finally {
                        DBUtils.closeAll(conn, pstmt, rs);
                    }
                }
            } else {
                System.out.println("未找到订单ID为 " + orderId + " 的订单");
                totalAmountField.setText("");
                taxAmountField.setText("");
            }
        } catch (Exception e) {
            System.out.println("获取订单信息时发生错误: " + e.getMessage());
            e.printStackTrace();
            totalAmountField.setText("");
            taxAmountField.setText("");
        }
    }

    // 消息提示方法
    private void showInfo(String message) {
        JOptionPane.showMessageDialog(this, message, "提示", JOptionPane.INFORMATION_MESSAGE);
    }

    private void showWarning(String message) {
        JOptionPane.showMessageDialog(this, message, "警告", JOptionPane.WARNING_MESSAGE);
    }

    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    /**
     * 显示选择对话框
     */
    private SalesShipments showSelectionDialog(List<SalesShipments> shipments) {
        // 创建对话框
        JDialog dialog = new JDialog(this, "选择发货单", true);
        dialog.setLayout(new BorderLayout(10, 10));
        dialog.setSize(600, 400);
        dialog.setLocationRelativeTo(this);

        // 创建表格模型
        String[] columnNames = {"发货单ID", "发货单号", "关联订单ID", "发货日期", "承运商", "物流单号"};
        Object[][] data = new Object[shipments.size()][6];
        for (int i = 0; i < shipments.size(); i++) {
            SalesShipments shipment = shipments.get(i);
            data[i][0] = shipment.getShipmentId();
            data[i][1] = shipment.getShipmentNumber();
            data[i][2] = shipment.getOrderId();
            data[i][3] = shipment.getShipmentDate() != null ? shipment.getShipmentDate().format(DATE_FORMATTER) : "";
            data[i][4] = shipment.getCarrier();
            data[i][5] = shipment.getTrackingNumber();
        }

        JTable table = new JTable(data, columnNames);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        table.setRowHeight(30);

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        dialog.add(scrollPane, BorderLayout.CENTER);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        JButton selectButton = new JButton("选择");
        JButton cancelButton = new JButton("取消");

        // 设置按钮样式
        selectButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        selectButton.setPreferredSize(new Dimension(100, 35));
        cancelButton.setPreferredSize(new Dimension(100, 35));

        final SalesShipments[] selected = {null};

        selectButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                selected[0] = shipments.get(selectedRow);
                dialog.dispose();
            } else {
                showWarning("请选择一个发货单");
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(selectButton);
        buttonPanel.add(cancelButton);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        // 显示对话框
        dialog.setVisible(true);

        return selected[0];
    }

    /**
     * 为文本字段添加实时验证
     */
    private void addFieldValidation(JTextField field, String fieldName, boolean isRequired) {
        field.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                validateField(field, fieldName, isRequired);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                validateField(field, fieldName, isRequired);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                validateField(field, fieldName, isRequired);
            }
        });
    }

    /**
     * 验证文本字段
     */
    private void validateField(JTextField field, String fieldName, boolean isRequired) {
        String value = field.getText().trim();
        if (isRequired && value.isEmpty()) {
            field.setBorder(BorderFactory.createLineBorder(Color.RED));
            field.setToolTipText(fieldName + "不能为空");
        } else if (fieldName.contains("ID") && !value.isEmpty()) {
            try {
                Integer.parseInt(value);
                field.setBorder(BorderFactory.createLineBorder(Color.GREEN));
                field.setToolTipText(null);
            } catch (NumberFormatException e) {
                field.setBorder(BorderFactory.createLineBorder(Color.RED));
                field.setToolTipText(fieldName + "必须是数字");
            }
        } else {
            field.setBorder(BorderFactory.createLineBorder(Color.GREEN));
            field.setToolTipText(null);
        }
    }

    /**
     * 验证日期字段
     */
    private void validateDateField() {
        String date = shipDateField.getText().trim();
        if (date.isEmpty()) {
            shipDateField.setBorder(BorderFactory.createLineBorder(Color.RED));
            shipDateField.setToolTipText("发货日期不能为空");
            return;
        }
        try {
            LocalDate.parse(date, DATE_FORMATTER);
            shipDateField.setBorder(BorderFactory.createLineBorder(Color.GREEN));
            shipDateField.setToolTipText(null);
        } catch (DateTimeParseException e) {
            shipDateField.setBorder(BorderFactory.createLineBorder(Color.RED));
            shipDateField.setToolTipText("日期格式不正确，请使用yyyy-MM-dd格式");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(UpdateSalesShipment::new);
    }
}